package com.atguigu.tingshu.live.util;

import com.atguigu.tingshu.live.config.LiveProperties;
import com.atguigu.tingshu.vo.live.TencentLiveAddressVo;
import jakarta.annotation.Resource;

import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

@Component
public class LiveAddUtil {
    @Resource
    private LiveProperties liveProperties;

    public TencentLiveAddressVo getAddressUrl(String streamName, Date txTime) {

        //过期时间
        long exTime = txTime.getTime() / 1000;

        // 推流最终地址
        String pushUrl = "webrtc://" + liveProperties.getPushDomain() + "/" + liveProperties.getAppName() + "/" + streamName + "?" + exTime;
        //播放地址
        String playUrl = "webrtc://" + liveProperties.getPullDomain() + "/" + liveProperties.getAppName() + "/" + streamName + "?" + exTime;
        TencentLiveAddressVo tencentLiveAddressVo = new TencentLiveAddressVo();
        tencentLiveAddressVo.setPushWebRtcUrl(pushUrl);
        tencentLiveAddressVo.setPullWebRtcUrl(playUrl);
        return tencentLiveAddressVo;
    }

    private static final char[] DIGITS_LOWER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /*
     * KEY+ streamName + txTime
     */
    private static String getSafeUrl(String key, String streamName, long txTime) {
        String input = key +
                streamName +
                Long.toHexString(txTime).toUpperCase();

        String txSecret = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            txSecret = byteArrayToHexString(
                    messageDigest.digest(input.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return txSecret == null ? "" :
                "txSecret=" +
                        txSecret +
                        "&" +
                        "txTime=" +
                        Long.toHexString(txTime).toUpperCase();
    }

    private static String byteArrayToHexString(byte[] data) {
        char[] out = new char[data.length << 1];

        for (int i = 0, j = 0; i < data.length; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return new String(out);
    }
}
